//
//  LeftSlideVC.swift
//  ShareUmbrella
//
//  Created by duanmingyang on 2017/9/15.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SDWebImage

class LeftSlideVC: YSBaseViewController,UITableViewDelegate,UITableViewDataSource{
    let kScreenHeight = UIScreen.main.bounds.size.height
    let kScreenWidth = UIScreen.main.bounds.size.width
    var selfTableView:UITableView!
    
    var nicknameLab:UILabel!
    var headIcon:UIButton!
    
    var dataArr = ["我的账户","我的帮助","积分商城","用户反馈","设置","退出"]
    var imgArr = ["账户","帮助","积分商城","反馈","设置","退出"]
    
    override func setup() {
        super.setup()
    }
    
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.home.title")
        
        self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
        
        self.initBackgourndViewColor()
        self.addSelfTableView()
        self.getUserInfo()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        let url = UserService.sharedInstance.headLogo.value ?? ""
        super.viewWillAppear(animated)
        self.nicknameLab.text = UserService.sharedInstance.name.value
        self.nicknameLab.frame = CGRect(x:140, y:60, width:160, height:120)
        self.nicknameLab.sizeToFit()
        self.headIcon.sd_setBackgroundImage(with: URL(string: url), for: UIControlState.normal,placeholderImage:  UIImage(named: "头像"), options: SDWebImageOptions.highPriority, completed: nil)
        //self.headIcon.sd_setBackgroundImage(with: <#T##URL?#>, for: <#T##UIControlState#>, placeholderImage: <#T##UIImage?#>, options: <#T##SDWebImageOptions#>, completed: <#T##SDExternalCompletionBlock?##SDExternalCompletionBlock?##(UIImage?, Error?, SDImageCacheType, URL?) -> Void#>)
        
    }
    
    //
    override func buildRx() {
        super.buildRx()
    }
    
    //RGB
    func RGB(r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor{
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: 1.0)
    }
    
    //初始化背景颜色
    func initBackgourndViewColor() {
        self.view.backgroundColor = UIColor.white
    }
    
    //跳转到个人心中
    func switchMineCenterVC(){
        self.revealViewController()!.revealToggle(nil)
        //let vc = MineCenterVC(config: UserConfiges())
        //self.fontVC?.ys.push(vc)
        self.fontVC?.ys.push(MyInfoVC())
    }
    
    //用户信息
    func getUserInfo() -> Void {
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.userInfo(token: Auth.token))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            guard let _ = self else {
                return
            }
            
            guard let userInfo = data else{
                return
            }
            
            UserService.sharedInstance.name.value = userInfo["data"]["nickname"].string ?? ""
            UserService.sharedInstance.km.value = userInfo["data"]["sharedistance"].string ?? "0"
            UserService.sharedInstance.times.value = userInfo["data"]["sharemins"].string ?? "0"
            UserService.sharedInstance.point.value = userInfo["data"]["point"].string ?? "0"
            UserService.sharedInstance.count.value = userInfo["data"]["sharetimes"].string ?? "0"
            UserService.sharedInstance.headLogo.value = userInfo["data"]["avatorUrl"].string
            
            self?.nicknameLab.text = userInfo["data"]["nickname"].string ?? "昵称"
            self?.headIcon.sd_setBackgroundImage(with: URL(string: UserService.sharedInstance.headLogo.value ?? ""), for: UIControlState.normal,placeholderImage:  UIImage(named: "空白头像"), options: SDWebImageOptions.highPriority, completed: nil)
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
        })
        
    }
    
    //添加一个tableview
    func addSelfTableView(){
        
        let v = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 245))
        
        let bg = UIImageView.init(frame: CGRect(x: 0, y: 0, width: 320, height: 255))
        bg.image = UIImage.init(named: "图案")
        v.addSubview(bg)
        
        let shadow = UIView.init(frame: CGRect(x: 30, y: 38, width: 72, height: 72))
        shadow.layer.cornerRadius = 36
        shadow.layer.borderWidth = 3
        shadow.layer.borderColor = UIColor.white.cgColor
        shadow.layer.shadowOffset = CGSize(width: 1,height: 1)
        shadow.layer.shadowOpacity = 4
        shadow.layer.shadowRadius = 2
        v.addSubview(shadow)
        
        headIcon = UIButton.init(frame: CGRect(x: 30, y: 38, width: 72, height: 72))
        headIcon.layer.cornerRadius = 36
        headIcon.layer.borderWidth = 3
        headIcon.layer.borderColor = UIColor.white.cgColor
        headIcon.layer.shadowOffset = CGSize(width: 0,height: 1)
        headIcon.layer.shadowOpacity = 4
        headIcon.layer.shadowRadius = 2
        headIcon.clipsToBounds = true;
        headIcon.setBackgroundImage(UIImage.init(named: "头像"), for: UIControlState.normal)
        headIcon.addTarget(self, action: #selector(switchMineCenterVC), for: UIControlEvents.touchUpInside)
        v.addSubview(headIcon)
        
        nicknameLab = UILabel.init()
        nicknameLab.backgroundColor = UIColor.clear;
        nicknameLab.frame = CGRect(x:140, y:60, width:160, height:120)
        nicknameLab.text = ""
        nicknameLab.textColor = UIColor.white
        nicknameLab.font = UIFont.systemFont(ofSize: 30)
        nicknameLab.lineBreakMode = NSLineBreakMode.byWordWrapping
        nicknameLab.numberOfLines = 0
        //nicknameLab.sizeToFit()
        //nicknameLab.contentMode = UIViewContentMode.top
        v.addSubview(nicknameLab)
        
        let nicknameBtn = UIButton.init(frame: CGRect(x: 120, y: 50, width: 320, height: 120))
        nicknameBtn.addTarget(self, action: #selector(switchMineCenterVC), for: UIControlEvents.touchUpInside)
        v.addSubview(nicknameBtn)
        
        
        selfTableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), style: UITableViewStyle.plain)
        selfTableView.dataSource = self
        selfTableView.delegate = self
        selfTableView.backgroundColor = UIColor.clear
        selfTableView.separatorStyle = UITableViewCellSeparatorStyle.none;
        selfTableView.showsHorizontalScrollIndicator = false
        selfTableView.showsVerticalScrollIndicator = false
        selfTableView.tableHeaderView = v
        selfTableView.isScrollEnabled = false
        self.view.addSubview(selfTableView)
    }
    
    //MARK:UITableView DataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let iderntify:String = "swiftCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: iderntify) as? LeftSlideCell
        if(cell == nil){
            cell=LeftSlideCell(style: UITableViewCellStyle.default
                , reuseIdentifier: iderntify);
            //cell?.selectionStyle = UITableViewCellSelectionStyle.none
            
        }
        let section = indexPath.section
        
        cell?.icon?.image = UIImage.init(named: imgArr[section])
        cell?.titleLabel?.text = dataArr[section]
        return cell!
    }
    
    //MARK:UITableView Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selfTableView?.deselectRow(at: indexPath, animated: true)
        
        let section = indexPath.section
        let str = dataArr[section]
        
        if(str == "我的账户"){
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(MyAccountVC())
        }else if(str == "我的帮助"){
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(MyHelpSetVC())
        }else if(str == "积分商城"){
            self.revealViewController()!.revealToggle(nil)
            //self.fontVC?.ys.push(PointShopVC())
            self.fontVC?.ys.push(IntegralShopVC())
        }else if(str == "用户反馈"){
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(FadebackVC())
        }else if(str == "设置"){
            self.revealViewController()!.revealToggle(nil)
            self.fontVC?.ys.push(SettingVC())
        }else if(str == "退出"){
            let optionMenu = UIAlertController(title: nil, message:"退出后不会删除任何历史数据", preferredStyle:.actionSheet)
            let exitAction = UIAlertAction(title: "确定", style: .default, handler:{ (alert: UIAlertAction!) -> Void in
                self.revealViewController()!.revealToggle(nil)
                Auth.logout()
            })
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (alert: UIAlertAction!) -> Void in
                
            })
            
            optionMenu.addAction(exitAction)
            optionMenu.addAction(cancelAction)
            
            self.present(optionMenu, animated: true, completion: nil)
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(section == 0){
            return 0
        }
        return 20
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 20))
        if(section == 0){
            view.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 0)
        }
        return view
    }
}

extension LeftSlideVC {
    var fontVC: UIViewController? {
        return APP.currentVC
    }
}

